<?php

namespace App\Services;

use App\Enum\ActivityEnum;
use App\Enum\TravelEnum;
use App\Models\ActivityApplicationModel;
use App\Models\ActivityModel;
use App\Models\CommunityModel;
use App\resources\Api\GetAtivityCollection;
use App\resources\Api\GetAtivityInfoCollection;
use App\Services\Tools\HelpService;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use Illuminate\Support\Facades\DB;

class ActivityService
{
    /**
     * 活动列表
     * @param array $params
     */
    public static function getActivityList(array $params = [])
    {
        $obj = ActivityModel::query()
            ->select('id', 'title', 'platform_id', 'description', 'start_time', 'end_time', 'image_url', 'state')
            ->where('community_id', $params['community_id']);
        // 村民默认只查看审核通过且进行中的。
        if (request()->appId == TravelEnum::PLATFORM_VILLAGER) {
            //查询在活动时间内的活动
            $obj = $obj->where('state', 1)
                ->where('start_time', '<=', date('Y-m-d'))
                ->where('end_time', '>=', date('Y-m-d'));
        } else {
            // 居委可按照状态查看
            $state = \request()->get('state');
            if( !in_array($state,[0,1,2])) {
                throw new \Exception('超出状态范围');
            }
            $obj = $obj->where('state',$state)->where('end_time','>', date('Y-m-d',strtotime('-7 days')));
        }
        $data = $obj->orderBy("start_time", "desc")
            ->paginate(HelpService::perPage());
        return GetAtivityCollection::collection($data);
    }

    public static function getActivityJoinList(array $params = [])
    {
        //查询我参与的活动
        $data = ActivityModel::query()
            ->leftJoin('activity_application as aa', 'activity.id', '=', 'aa.activity_id')
            ->select('activity.*')
            ->where('aa.user_id', request()->userId)
            ->where('activity.state', 1)
            ->where('aa.state', 1)
            ->orderBy("activity.created_at", "desc")
            ->paginate(HelpService::perPage());
        return GetAtivityCollection::collection($data);
    }

    /**
     * 活动信息
     * @param int $id
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public static function getActivity(int $id = 0, int $userId = 0, int $platformId): array
    {
        if (!$id || !$userId) {
            throw new \Exception('参数错误');
        }

        $data = ActivityModel::query()->find($id);
        if (!$data) {
            throw new \Exception('活动不存在');
        }
        $data = $data->toArray();
        $data['community_name'] = CommunityModel::query()->where('id', $data['community_id'])->value('community_name');

        $arr = [
            'activity_id' => $id,
            'user_id' => $userId,
            'user_type' =>$platformId,
            'state' => 1
        ];
        $userApplied = ActivityApplicationModel::query()->where($arr)->exists();

        //时间判断
        $startTime = $data['start_time'] ? strtotime($data['start_time']) : 0;
        $endTime = $data['end_time'] ? strtotime($data['end_time']) : 0;

        $currentTime = time();

        $data['status_name'] = ActivityEnum::STATUS_NAMES[$data['state']];

        if( $data['state'] == ActivityEnum::STATUS_PASS ) {
            if ($currentTime < $startTime) {
                $data['status_name'] = "未开始";
            } elseif ($currentTime > $endTime) {
                $data['status_name'] = "已结束";
            } else {
                $data['status_name'] = "进行中";
            }
        }

        // 是否报名成功
        $data['apply_state'] = $userApplied ? 1 : 0;
        return $data;
    }


    /**
     * 活动报名
     * @param array $params
     * @return true
     * @throws \Exception
     */
    public static function activityAdd($user, array $params = []): bool
    {
        $title = $params['title'] ?? '';
        $description = $params['description'] ?? '';
        $startTime = $params['start_time'] ?? '';
        $endTime = $params['end_time'] ?? '';
        $num = $params['num'] ?? '';
        $volunteerNum = $params['volunteer_num'] ?? '';
        $organizer = $params['organizer'] ?? '';
        $organizerPhone = $params['organizer_phone'] ?? '';
        $startAddress = $params['start_address'] ?? '';
        $startAddressDetail = $params['start_address_detail'] ?? '';
        $startLocationLng = $params['start_location_lng'] ?? '';
        $startLocationLat = $params['start_location_lat'] ?? '';
        $endAddress = $params['end_address'] ?? '';
        $endAddressDetail = $params['end_address_detail'] ?? '';
        $endLocationLng = $params['end_location_lng'] ?? '';
        $endLocationLat = $params['end_location_lat'] ?? '';
        $distance = $params['distance'] ?? 0;
        $vehicleUseDate = $params['vehicle_use_date'] ?? 0;
        $vehicleUseDays = $params['vehicle_use_days'] ?? 0;
        $communityId = CommonService::getCommunity()['community_id'];
        if (empty($title)) {
            throw new \Exception('活动标题不能为空');
        }
        if (empty($description)) {
            throw new \Exception('活动描述不能为空');
        }
        if (empty($startTime)) {
            throw new \Exception('活动开始时间不能为空');
        }
        if (empty($endTime)) {
            throw new \Exception('活动结束时间不能为空');
        }
        if ($startTime > $endTime) {
            throw new \Exception('活动开始时间不能大于结束时间');
        }
        if (empty($num <= 0) && $num <= 0) {
            throw new \Exception('活动人数不能小于0');
        }
        if (empty($organizer)) {
            throw new \Exception('活动组织者不能为空');
        }
        if(empty($organizerPhone)){
            throw new \Exception('活动组织者电话不能为空');
        }
        if (empty($startAddress)) {
            throw new \Exception('活动开始地址不能为空');
        }
        if (empty($startLocationLng)) {
            throw new \Exception('活动开始坐标不能为空');
        }
        if (empty($endAddress)) {
            throw new \Exception('活动结束地址不能为空');
        }
        if (empty($endLocationLng)) {
            throw new \Exception('活动结束坐标不能为空');
        }

        $data = [
            'title' => $title,
            'description' => $description,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'num' => $num,
            'user_id'   => $user->id,
            'creator'   => $user->phone,
            'volunteer_num' => $volunteerNum,
            'community_id' => $communityId,
            'platform_id' => request()->appId,
            'start_address' => $startAddress,
            'start_address_detail' => $startAddressDetail,
            'start_location_lat' => $startLocationLat,
            'start_location_lng' => $startLocationLng,
            'end_address' => $endAddress,
            'end_address_detail' => $endAddressDetail,
            'end_location_lat' => $endLocationLat,
            'end_location_lng' => $endLocationLng,
            'distance' => $distance,
            'vehicle_use_date' => strtotime($vehicleUseDate),
            'vehicle_use_days' => $vehicleUseDays,
            'organizer' => $organizer,
            'organizer_phone' => $organizerPhone
        ];

        $res = ActivityModel::query()->create($data);
        if (!$res) {
            throw new \Exception('添加失败');
        }

        return true;
    }

    /**
     * 确认发布活动
     * activityConfirm
     * @param array $post
     * @return true
     * @throws \Exception
     * @author ninetyseven.
     * @date 2023/7/6
     */
    public static function activityConfirm(array $post = []): bool
    {
        $id = $post['id'] ?? 0;
        $check = $post['is_confirm'] ?? 1;

        if (!$id) {
            throw new \Exception('参数错误');
        }
        $data = ActivityModel::query()->find($id);
        if (!$data) {
            throw new \Exception('活动不存在');
        }

        //确认发布
        if($check == 1) {
            $data->platform_id = request()->appId;
        }else{
            $data->state = 3;
        }

        $res = $data->save();
        if (!$res) {
            throw new \Exception('操作失败');
        }

        return true;
    }
}
